{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.1"
    },
    "colab": {
      "provenance": []
    }
  },
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0PS2uZBu_us2"
      },
      "source": [
        "<p style=\"align: center;\"><img align=center src=\"https://s8.hostingkartinok.com/uploads/images/2018/08/308b49fcfbc619d629fe4604bceb67ac.jpg\" width=600 height=500/></p>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "JR3NCvhR_us_"
      },
      "source": [
        "<h3 style=\"text-align: center;\"><b>Школа глубокого обучения ФПМИ МФТИ. Осень 2021</b></h3>\n",
        "\n",
        "<h1 style=\"text-align: center;\"><b>Библиотека NumPy</b></h1>"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "aZUMBmav_utA"
      },
      "source": [
        "***Мы могли писать такой код и ни о чем не задумываться.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "FSHek2dN_utA",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "faa592ad-4ac0-4fb2-9bc3-e2ef82451648"
      },
      "source": [
        "%%time\n",
        "arr = []\n",
        "n = 10**7\n",
        "for i in range(n):\n",
        "    arr.append(i*5)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "CPU times: user 1.44 s, sys: 213 ms, total: 1.65 s\n",
            "Wall time: 1.67 s\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "fejD4AKE_utB"
      },
      "source": [
        "***Или такой...***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "EtR2sF38_utB",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e113a189-68d1-4cdf-f07a-bd70c1b8c94d"
      },
      "source": [
        "%%time\n",
        "def summ(a):\n",
        "    ans = 0\n",
        "    for i in a:\n",
        "        ans += i\n",
        "    return ans\n",
        "\n",
        "arr = range(10**7)\n",
        "\n",
        "print(summ(arr))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "49999995000000\n",
            "CPU times: user 680 ms, sys: 17.7 ms, total: 697 ms\n",
            "Wall time: 700 ms\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "J1upNY5z_utC"
      },
      "source": [
        "# Библиотека Numpy.\n",
        "- ***``Numpy`` - это библиотека Python для вычислительно эффективных операций с многомерными массивами, предназначенная в основном для научных вычислений.***\n",
        "\n",
        "\n",
        "- ***Пакет ``Numpy`` предоставляет $n$-мерные однородные массивы (все элементы одного типа) в них нельзя вставить или удалить элемент в произвольном месте. В ``Numpy`` реализовано много операций над массивами в целом.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "tkN1DwOt_utC",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e25a5489-588c-48f5-e81c-d71fcab97ff1"
      },
      "source": [
        "!which python"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "/usr/local/bin/python\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vkt3rS0X_utC"
      },
      "source": [
        "# !conda install numpy\n",
        "# !pip3 install numpy"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-ACVD36u_utD"
      },
      "source": [
        "import numpy as np"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "G7t67Mlv_utD"
      },
      "source": [
        "## 1. Одномерные массивы"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-p1555UI_utD",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "74fa557e-4da6-4a76-95dd-1070117fcea6"
      },
      "source": [
        "a = [1, 2, 3]\n",
        "b = np.array(a, dtype='float64')\n",
        "print(type(b), type(a))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'numpy.ndarray'> <class 'list'>\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Z6yyCigN_utD"
      },
      "source": [
        "***Если типы разные, то идет неявный каст к одному.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "fXDm6tv__utE",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "cff39623-5ef4-49ac-c5c5-9e32eb1ff8f7"
      },
      "source": [
        "a = [1, 2, 'a']\n",
        "b = np.array(a)\n",
        "print(\"Для list:\", type(a[0]),\n",
        "      \"\\nДля np.array:\", type(b[0]))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Для list: <class 'int'> \n",
            "Для np.array: <class 'numpy.str_'>\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "lv_tlRAa_utE",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f1aa6896-4757-4f51-d13c-834e166b28b4"
      },
      "source": [
        "d = np.array([1, 2, 3])\n",
        "d"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([1, 2, 3])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 7
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "4I5-6h3p_utE",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "25cd7f31-5560-4299-91eb-fb877108be7e"
      },
      "source": [
        "type(d)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "numpy.ndarray"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 8
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qw38Lnfj_utF"
      },
      "source": [
        "***Можем посмотреть на все методы класса ``ndarray``.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "URGqdbLs_utF",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "734cf3e1-1ec7-48db-a5b3-b9a8b1b547cc"
      },
      "source": [
        "set(dir(b)) - set(dir(object))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "{'T',\n",
              " '__abs__',\n",
              " '__add__',\n",
              " '__and__',\n",
              " '__array__',\n",
              " '__array_finalize__',\n",
              " '__array_function__',\n",
              " '__array_interface__',\n",
              " '__array_prepare__',\n",
              " '__array_priority__',\n",
              " '__array_struct__',\n",
              " '__array_ufunc__',\n",
              " '__array_wrap__',\n",
              " '__bool__',\n",
              " '__complex__',\n",
              " '__contains__',\n",
              " '__copy__',\n",
              " '__deepcopy__',\n",
              " '__delitem__',\n",
              " '__divmod__',\n",
              " '__float__',\n",
              " '__floordiv__',\n",
              " '__getitem__',\n",
              " '__iadd__',\n",
              " '__iand__',\n",
              " '__ifloordiv__',\n",
              " '__ilshift__',\n",
              " '__imatmul__',\n",
              " '__imod__',\n",
              " '__imul__',\n",
              " '__index__',\n",
              " '__int__',\n",
              " '__invert__',\n",
              " '__ior__',\n",
              " '__ipow__',\n",
              " '__irshift__',\n",
              " '__isub__',\n",
              " '__iter__',\n",
              " '__itruediv__',\n",
              " '__ixor__',\n",
              " '__len__',\n",
              " '__lshift__',\n",
              " '__matmul__',\n",
              " '__mod__',\n",
              " '__mul__',\n",
              " '__neg__',\n",
              " '__or__',\n",
              " '__pos__',\n",
              " '__pow__',\n",
              " '__radd__',\n",
              " '__rand__',\n",
              " '__rdivmod__',\n",
              " '__rfloordiv__',\n",
              " '__rlshift__',\n",
              " '__rmatmul__',\n",
              " '__rmod__',\n",
              " '__rmul__',\n",
              " '__ror__',\n",
              " '__rpow__',\n",
              " '__rrshift__',\n",
              " '__rshift__',\n",
              " '__rsub__',\n",
              " '__rtruediv__',\n",
              " '__rxor__',\n",
              " '__setitem__',\n",
              " '__setstate__',\n",
              " '__sub__',\n",
              " '__truediv__',\n",
              " '__xor__',\n",
              " 'all',\n",
              " 'any',\n",
              " 'argmax',\n",
              " 'argmin',\n",
              " 'argpartition',\n",
              " 'argsort',\n",
              " 'astype',\n",
              " 'base',\n",
              " 'byteswap',\n",
              " 'choose',\n",
              " 'clip',\n",
              " 'compress',\n",
              " 'conj',\n",
              " 'conjugate',\n",
              " 'copy',\n",
              " 'ctypes',\n",
              " 'cumprod',\n",
              " 'cumsum',\n",
              " 'data',\n",
              " 'diagonal',\n",
              " 'dot',\n",
              " 'dtype',\n",
              " 'dump',\n",
              " 'dumps',\n",
              " 'fill',\n",
              " 'flags',\n",
              " 'flat',\n",
              " 'flatten',\n",
              " 'getfield',\n",
              " 'imag',\n",
              " 'item',\n",
              " 'itemset',\n",
              " 'itemsize',\n",
              " 'max',\n",
              " 'mean',\n",
              " 'min',\n",
              " 'nbytes',\n",
              " 'ndim',\n",
              " 'newbyteorder',\n",
              " 'nonzero',\n",
              " 'partition',\n",
              " 'prod',\n",
              " 'ptp',\n",
              " 'put',\n",
              " 'ravel',\n",
              " 'real',\n",
              " 'repeat',\n",
              " 'reshape',\n",
              " 'resize',\n",
              " 'round',\n",
              " 'searchsorted',\n",
              " 'setfield',\n",
              " 'setflags',\n",
              " 'shape',\n",
              " 'size',\n",
              " 'sort',\n",
              " 'squeeze',\n",
              " 'std',\n",
              " 'strides',\n",
              " 'sum',\n",
              " 'swapaxes',\n",
              " 'take',\n",
              " 'tobytes',\n",
              " 'tofile',\n",
              " 'tolist',\n",
              " 'tostring',\n",
              " 'trace',\n",
              " 'transpose',\n",
              " 'var',\n",
              " 'view'}"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 9
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FvUaUOWY_utF"
      },
      "source": [
        "***Например узнаем размер массива.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "EzotaqMm_utF"
      },
      "source": [
        "arr = np.array([5, 6, 2, 1, 10], dtype='int32')"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "cFzpqEys_utG",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a5a94535-13ff-4f1a-db56-9d09bdc34234"
      },
      "source": [
        "arr.nbytes"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "20"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 11
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "K4JWtd2q_utG"
      },
      "source": [
        "***Если вы не знаете нужной функции, но понимаете, чего хотите, тогда можно воспользоваться поиском в документации.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "A684TRSO_utG",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "63ccf169-d578-4a1e-b69d-9420db37fa21"
      },
      "source": [
        "np.lookfor('mean value of array') "
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "Search results for 'mean value of array'\n",
            "----------------------------------------\n",
            "numpy.ma.mean\n",
            "    Returns the average of the array elements along given axis.\n",
            "numpy.mean\n",
            "    Compute the arithmetic mean along the specified axis.\n",
            "numpy.nanmean\n",
            "    Compute the arithmetic mean along the specified axis, ignoring NaNs.\n",
            "numpy.put\n",
            "    Replaces specified elements of an array with given values.\n",
            "numpy.full\n",
            "    Return a new array of given shape and type, filled with `fill_value`.\n",
            "numpy.digitize\n",
            "    Return the indices of the bins to which each value in input array belongs.\n",
            "numpy.unpackbits\n",
            "    Unpacks elements of a uint8 array into a binary-valued output array.\n",
            "numpy.nanquantile\n",
            "    Compute the qth quantile of the data along the specified axis,\n",
            "numpy.ma.dot\n",
            "    Return the dot product of two arrays.\n",
            "numpy.count_nonzero\n",
            "    Counts the number of non-zero values in the array ``a``.\n",
            "numpy.ma.fix_invalid\n",
            "    Return input with invalid data masked and replaced by a fill value.\n",
            "numpy.matrix.partition\n",
            "    Rearranges the elements in the array in such a way that the value of the\n",
            "numpy.ma.MaskedArray.filled\n",
            "    Return a copy of self, with masked values filled with a given value.\n",
            "numpy.ma.MaskedArray.partition\n",
            "    Rearranges the elements in the array in such a way that the value of the\n",
            "numpy.core._multiarray_umath.unpackbits\n",
            "    Unpacks elements of a uint8 array into a binary-valued output array.\n",
            "numpy.exp\n",
            "    Calculate the exponential of all elements in the input array.\n",
            "numpy.ptp\n",
            "    Range of values (maximum - minimum) along an axis.\n",
            "numpy.sum\n",
            "    Sum of array elements over a given axis.\n",
            "numpy.var\n",
            "    Compute the variance along the specified axis.\n",
            "numpy.copy\n",
            "    Return an array copy of the given object.\n",
            "numpy.prod\n",
            "    Return the product of array elements over a given axis.\n",
            "numpy.block\n",
            "    Assemble an nd-array from nested lists of blocks.\n",
            "numpy.copyto\n",
            "    Copies values from one array to another, broadcasting as necessary.\n",
            "numpy.median\n",
            "    Compute the median along the specified axis.\n",
            "numpy.nanmax\n",
            "    Return the maximum of an array or maximum along an axis, ignoring any\n",
            "numpy.nanmin\n",
            "    Return minimum of an array or minimum along an axis, ignoring any NaNs.\n",
            "numpy.nansum\n",
            "    Return the sum of array elements over a given axis treating Not a\n",
            "numpy.nanvar\n",
            "    Compute the variance along the specified axis, while ignoring NaNs.\n",
            "numpy.allclose\n",
            "    Returns True if two arrays are element-wise equal within a tolerance.\n",
            "numpy.gradient\n",
            "    Return the gradient of an N-dimensional array.\n",
            "numpy.nanmedian\n",
            "    Compute the median along the specified axis, while ignoring NaNs.\n",
            "numpy.ones_like\n",
            "    Return an array of ones with the same shape and type as a given array.\n",
            "numpy.lib.recfunctions.assign_fields_by_name\n",
            "    Assigns values from one structured array to another by field name.\n",
            "numpy.percentile\n",
            "    Compute the q-th percentile of the data along the specified axis.\n",
            "numpy.zeros_like\n",
            "    Return an array of zeros with the same shape and type as a given array.\n",
            "numpy.ma.exp\n",
            "    Calculate the exponential of all elements in the input array.\n",
            "numpy.chararray.copy\n",
            "    Return a copy of the array.\n",
            "numpy.ma.var\n",
            "    Compute the variance along the specified axis.\n",
            "numpy.chararray.view\n",
            "    New view of array with the same data.\n",
            "numpy.nanpercentile\n",
            "    Compute the qth percentile of the data along the specified axis,\n",
            "numpy.chararray.astype\n",
            "    Copy of the array, cast to a specified type.\n",
            "numpy.ma.median\n",
            "    Compute the median along the specified axis.\n",
            "numpy.linalg.svd\n",
            "    Singular Value Decomposition.\n",
            "numpy.ma.MaskedArray.mean\n",
            "    Returns the average of the array elements along given axis.\n",
            "numpy.ma.MaskedArray.dot\n",
            "    Masked dot product of two arrays. Note that `out` and `strict` are\n",
            "numpy.ma.MaskedArray.var\n",
            "    Compute the variance along the specified axis.\n",
            "numpy.ma.MaskedArray.copy\n",
            "    Return a copy of the array.\n",
            "numpy.core._multiarray_umath.copyto\n",
            "    Copies values from one array to another, broadcasting as necessary.\n",
            "numpy.polynomial.polyutils.trimcoef\n",
            "    Remove \"small\" \"trailing\" coefficients from a polynomial.\n",
            "numpy.pad\n",
            "    Pad an array.\n",
            "numpy.std\n",
            "    Compute the standard deviation along the specified axis.\n",
            "numpy.take\n",
            "    Take elements from an array along an axis.\n",
            "numpy.isnan\n",
            "    Test element-wise for NaN and return result as a boolean array.\n",
            "numpy.nditer\n",
            "    Efficient multi-dimensional iterator object to iterate over arrays.\n",
            "numpy.polyfit\n",
            "    Least squares polynomial fit.\n",
            "numpy.reshape\n",
            "    Gives a new shape to an array without changing its data.\n",
            "numpy.quantile\n",
            "    Compute the q-th quantile of the data along the specified axis.\n",
            "numpy.full_like\n",
            "    Return a full array with the same shape and type as a given array.\n",
            "numpy.empty_like\n",
            "    Return a new array with the same shape and type as a given array.\n",
            "numpy.ma.ptp\n",
            "    Return (maximum - minimum) along the given dimension\n",
            "numpy.ma.anom\n",
            "    Compute the anomalies (deviations from the arithmetic mean)\n",
            "numpy.fft.ifft2\n",
            "    Compute the 2-dimensional inverse discrete Fourier Transform.\n",
            "numpy.fft.ifftn\n",
            "    Compute the N-dimensional inverse discrete Fourier Transform.\n",
            "numpy.ma.ravel\n",
            "    Returns a 1D version of self, as a view.\n",
            "numpy.fft.irfftn\n",
            "    Compute the inverse of the N-dimensional FFT of real input.\n",
            "numpy.ma.polyfit\n",
            "    Least squares polynomial fit.\n",
            "numpy.linalg.cond\n",
            "    Compute the condition number of a matrix.\n",
            "numpy.linalg.norm\n",
            "    Matrix or vector norm.\n",
            "numpy.histogram_bin_edges\n",
            "    Function to calculate only the edges of the bins used by the `histogram`\n",
            "numpy.ma.MaskedArray.ptp\n",
            "    Return (maximum - minimum) along the given dimension\n",
            "numpy.ma.MaskedArray.anom\n",
            "    Compute the anomalies (deviations from the arithmetic mean)\n",
            "numpy.ma.MaskedArray.ravel\n",
            "    Returns a 1D version of self, as a view.\n",
            "numpy.random.Generator.wald\n",
            "    Draw samples from a Wald, or inverse Gaussian, distribution.\n",
            "numpy.polynomial.Hermite._fit\n",
            "    Least squares fit of Hermite series to data.\n",
            "numpy.core._multiarray_umath.empty_like\n",
            "    Return a new array with the same shape and type as a given array.\n",
            "numpy.random.RandomState.wald\n",
            "    Draw samples from a Wald, or inverse Gaussian, distribution.\n",
            "numpy.polynomial.HermiteE._fit\n",
            "    Least squares fit of Hermite series to data.\n",
            "numpy.polynomial.Laguerre._fit\n",
            "    Least squares fit of Laguerre series to data.\n",
            "numpy.polynomial.Legendre._fit\n",
            "    Least squares fit of Legendre series to data.\n",
            "numpy.polynomial.Chebyshev._fit\n",
            "    Least squares fit of Chebyshev series to data.\n",
            "numpy.polynomial.Polynomial._fit\n",
            "    Least-squares fit of a polynomial to data.\n",
            "numpy.random.Generator.lognormal\n",
            "    Draw samples from a log-normal distribution.\n",
            "numpy.random.RandomState.lognormal\n",
            "    Draw samples from a log-normal distribution.\n",
            "numpy.random.Generator.standard_normal\n",
            "    Draw samples from a standard Normal distribution (mean=0, stdev=1).\n",
            "numpy.einsum\n",
            "    einsum(subscripts, *operands, out=None, dtype=None, order='K',\n",
            "numpy.interp\n",
            "    One-dimensional linear interpolation.\n",
            "numpy.kaiser\n",
            "    Return the Kaiser window.\n",
            "numpy.nanstd\n",
            "    Compute the standard deviation along the specified axis, while\n",
            "numpy.average\n",
            "    Compute the weighted average along the specified axis.\n",
            "numpy.hamming\n",
            "    Return the Hamming window.\n",
            "numpy.hanning\n",
            "    Return the Hanning window.\n",
            "numpy.bartlett\n",
            "    Return the Bartlett window.\n",
            "numpy.blackman\n",
            "    Return the Blackman window.\n",
            "numpy.can_cast\n",
            "    Returns True if cast between data types can occur according to the\n",
            "numpy.random.RandomState.standard_normal\n",
            "    Draw samples from a standard Normal distribution (mean=0, stdev=1).\n",
            "numpy.isfinite\n",
            "    Test element-wise for finiteness (not infinity or not Not a Number).\n",
            "numpy.random.Generator.multivariate_normal\n",
            "    Draw random samples from a multivariate normal distribution.\n",
            "numpy.nan_to_num\n",
            "    Replace NaN with zero and infinity with large finite numbers (default\n",
            "numpy.random.RandomState.multivariate_normal\n",
            "    Draw random samples from a multivariate normal distribution.\n",
            "numpy.ma.copy\n",
            "    a.copy(order='C')\n",
            "numpy.fft.fft2\n",
            "    Compute the 2-dimensional discrete Fourier Transform\n",
            "numpy.fft.fftn\n",
            "    Compute the N-dimensional discrete Fourier Transform.\n",
            "numpy.fft.rfft\n",
            "    Compute the one-dimensional discrete Fourier Transform for real input.\n",
            "numpy.fft.rfftn\n",
            "    Compute the N-dimensional discrete Fourier Transform for real input.\n",
            "numpy.random.SFC64\n",
            "    BitGenerator for Chris Doty-Humphrey's Small Fast Chaotic PRNG.\n",
            "numpy.ma.empty_like\n",
            "    empty_like(prototype, dtype=None, order='K', subok=True, shape=None)\n",
            "numpy.random.Generator.f\n",
            "    Draw samples from an F distribution.\n",
            "numpy.random.RandomState.f\n",
            "    Draw samples from an F distribution.\n",
            "numpy.core._multiarray_umath.c_einsum\n",
            "    c_einsum(subscripts, *operands, out=None, dtype=None, order='K',\n",
            "numpy.core._multiarray_umath.can_cast\n",
            "    Returns True if cast between data types can occur according to the\n",
            "numpy.random.Generator.gamma\n",
            "    Draw samples from a Gamma distribution.\n",
            "numpy.random.Generator.gumbel\n",
            "    Draw samples from a Gumbel distribution.\n",
            "numpy.random.Generator.normal\n",
            "    Draw random samples from a normal (Gaussian) distribution.\n",
            "numpy.random.Generator.laplace\n",
            "    Draw samples from the Laplace or double exponential distribution with\n",
            "numpy.random.RandomState.gamma\n",
            "    Draw samples from a Gamma distribution.\n",
            "numpy.random.Generator.logistic\n",
            "    Draw samples from a logistic distribution.\n",
            "numpy.random.Generator.rayleigh\n",
            "    Draw samples from a Rayleigh distribution.\n",
            "numpy.random.Generator.vonmises\n",
            "    Draw samples from a von Mises distribution.\n",
            "numpy.random.RandomState.gumbel\n",
            "    Draw samples from a Gumbel distribution.\n",
            "numpy.random.RandomState.normal\n",
            "    Draw random samples from a normal (Gaussian) distribution.\n",
            "numpy.random.Generator.chisquare\n",
            "    Draw samples from a chi-square distribution.\n",
            "numpy.random.RandomState.laplace\n",
            "    Draw samples from the Laplace or double exponential distribution with\n",
            "numpy.random.Generator.standard_t\n",
            "    Draw samples from a standard Student's t distribution with `df` degrees\n",
            "numpy.random.RandomState.logistic\n",
            "    Draw samples from a logistic distribution.\n",
            "numpy.random.RandomState.rayleigh\n",
            "    Draw samples from a Rayleigh distribution.\n",
            "numpy.random.RandomState.vonmises\n",
            "    Draw samples from a von Mises distribution.\n",
            "numpy.random.RandomState.chisquare\n",
            "    Draw samples from a chi-square distribution.\n",
            "numpy.random.Generator.noncentral_f\n",
            "    Draw samples from the noncentral F distribution.\n",
            "numpy.random.RandomState.standard_t\n",
            "    Draw samples from a standard Student's t distribution with `df` degrees\n",
            "numpy.random.Generator.standard_gamma\n",
            "    Draw samples from a standard Gamma distribution.\n",
            "numpy.random.RandomState.noncentral_f\n",
            "    Draw samples from the noncentral F distribution.\n",
            "numpy.random.RandomState.standard_gamma\n",
            "    Draw samples from a standard Gamma distribution."
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "esVuiArA_utG"
      },
      "source": [
        "***Далее можно почитать документацию про контретную функцию.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Abcqb-QH_utH"
      },
      "source": [
        "?np.ma.mean"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "zLDAnd4G_utH"
      },
      "source": [
        "np.con*?"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "0B7cbpZU_utH"
      },
      "source": [
        "***Посмотрим на количественные характеристики ``ndarray``.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "cOsmLh3o_utI",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "78a3aa34-0cee-499f-b391-a48b8856770e"
      },
      "source": [
        "arr = np.array([[[1, 2, 3, 4],\n",
        "                [2, 3, 4, 3],\n",
        "                [1, 1, 1, 1]], \n",
        "                [[1, 2, 3, 4],\n",
        "                [2, 3, 4, 3],\n",
        "                [1, 1, 1, 1]]])\n",
        "print(arr)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[[1 2 3 4]\n",
            "  [2 3 4 3]\n",
            "  [1 1 1 1]]\n",
            "\n",
            " [[1 2 3 4]\n",
            "  [2 3 4 3]\n",
            "  [1 1 1 1]]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "AV1wsl-3_utI",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0cc8d554-e7b2-4fe5-9b28-933457faf341"
      },
      "source": [
        "print(\"len:\", len(arr), \"-- количество элементов по первой оси.\",\n",
        "      \"\\nsize:\", arr.size, \"-- всего элементов в матрице.\",\n",
        "      \"\\nndim:\", arr.ndim, \"-- размерность матрицы.\",\n",
        "      \"\\nshape:\", arr.shape, \"-- количество элементов по каждой оси.\")"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "len: 2 -- количество элементов по первой оси. \n",
            "size: 24 -- всего элементов в матрице. \n",
            "ndim: 3 -- размерность матрицы. \n",
            "shape: (2, 3, 4) -- количество элементов по каждой оси.\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "I_cLmq7l_utI"
      },
      "source": [
        "***Индексы.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "K2je6I4r_utI",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e71e654a-26d9-414f-8edc-2a6b6149eac5"
      },
      "source": [
        "a = np.array([1, 2, 3, 4])\n",
        "a[0], a[1]"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(1, 2)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 17
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "CXNCieKj_utJ"
      },
      "source": [
        "***Последний элемент.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Mf8ChIln_utJ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "d232339c-c45d-448f-f25c-9aa5229877af"
      },
      "source": [
        "a[-1]"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "4"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 18
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_-3TtUFk_utJ"
      },
      "source": [
        "***Можем изменять объекты массива.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bWMF-mIP_utJ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "98225940-6695-4e4b-dfce-f360fc07fd32"
      },
      "source": [
        "a[2] = -1\n",
        "a"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([ 1,  2, -1,  4])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 19
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "AV5RMk7m_utK"
      },
      "source": [
        "***``ndarray`` можно использовать в циклах. Но при этом теряется главное преимущество `Numpy` -- быстродействие. Всегда, когда это возможно, лучше использовать операции над массивами как едиными целыми.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "I7Gxx9Ev_utK",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7592de0a-bd27-405e-bbdf-d6c81607b588"
      },
      "source": [
        "for i in a:\n",
        "    print(i)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "1\n",
            "2\n",
            "-1\n",
            "4\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "nEba-JFt_utK"
      },
      "source": [
        "**Задача 1:** Создать numpy-массив, состоящий из первых четырех простых чисел, выведите его тип и размер:"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "UW0scZM2_utK",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "fa7eb326-11c2-4ce1-a9f3-90de96092fb7"
      },
      "source": [
        "# решение\n",
        "\n",
        "arr = np.array([2, 3, 5, 7])\n",
        "print(arr)\n",
        "print(arr.dtype)\n",
        "print(type(arr))\n",
        "print(arr.shape)\n",
        "print(arr.nbytes)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[2 3 5 7]\n",
            "int64\n",
            "<class 'numpy.ndarray'>\n",
            "(4,)\n",
            "32\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rY90YTcw_utL"
      },
      "source": [
        "## Создание массивов."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vVFo3DhS_utL",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "77007f57-2089-4ccf-f950-8229e7a3cd51"
      },
      "source": [
        "a = np.zeros(7) # массив из нулей\n",
        "b = np.ones(7, dtype=np.int16) # массив из единиц\n",
        "print(a)\n",
        "print(b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[0. 0. 0. 0. 0. 0. 0.]\n",
            "[1 1 1 1 1 1 1]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PIqEGFbD_utL"
      },
      "source": [
        "***Часто нужно создать нулевой массив такой же как другой.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "XNMiwpF5_utL",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0b082527-65a0-4571-dcd3-424f0a4bfb5b"
      },
      "source": [
        "c = np.zeros(7)\n",
        "c"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([0., 0., 0., 0., 0., 0., 0.])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 24
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "gl2IwKED_utL",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "98ddb5aa-f5ea-47ba-ccdc-0f81164a3561"
      },
      "source": [
        "c = np.zeros_like(b)\n",
        "c"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([0, 0, 0, 0, 0, 0, 0], dtype=int16)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 23
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "XiMc_ATd_utL"
      },
      "source": [
        "***Функция `np.arange` подобна `range`. Аргументы могут быть с плавающей точкой. Следует избегать ситуаций, когда (конец-начало)/шаг -- целое число, потому что в этом случае включение последнего элемента зависит от ошибок округления. Лучше, чтобы конец диапазона был где-то посредине шага.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "heQ6wJmM_utN",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "570d693f-3075-449d-d313-18f9bad8b7cf"
      },
      "source": [
        "a = np.arange(1, 16, 4)\n",
        "b = np.arange(5., 21, 2)\n",
        "c = np.arange(1, 10)\n",
        "d = np.arange(5)\n",
        "print(a)\n",
        "print(b)\n",
        "print(c)\n",
        "print(d)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ 1  5  9 13]\n",
            "[ 5.  7.  9. 11. 13. 15. 17. 19.]\n",
            "[1 2 3 4 5 6 7 8 9]\n",
            "[0 1 2 3 4]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "1WTiQphx_utO"
      },
      "source": [
        "***Последовательности чисел с постоянным шагом можно также создавать функцией `linspace`. Начало и конец диапазона включаются; последний аргумент -- число точек.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "OWrTQixa_utO",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "16956d0d-0eeb-4ff9-b244-5030f7b0274f"
      },
      "source": [
        "a = np.linspace(1, 15, 2)\n",
        "b = np.linspace(5, 12, 10)\n",
        "print(a)\n",
        "print(b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ 1. 15.]\n",
            "[ 5.          5.77777778  6.55555556  7.33333333  8.11111111  8.88888889\n",
            "  9.66666667 10.44444444 11.22222222 12.        ]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "tinv6a4U_utO"
      },
      "source": [
        "**Задача 2:** создать и вывести последовательность чисел от 10 до 32 с постоянным шагом, длина последовательности -- 12. Чему равен шаг?"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "RM2JGLL9_utO",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "48947b8b-c1cf-4bc1-f8f2-96ae427fd144"
      },
      "source": [
        "# решение\n",
        "\n",
        "a = np.linspace(10, 32, 12)\n",
        "print(a)\n",
        "print(a[1] - a[0])\n",
        "\n"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[10. 12. 14. 16. 18. 20. 22. 24. 26. 28. 30. 32.]\n",
            "2.0\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "kyBHmBlt_utO"
      },
      "source": [
        "***Последовательность чисел с постоянным шагом по логарифмической шкале от $10^0$ до $10^3$.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "ditH-nIm_utP",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4dfca252-71ab-4d79-fb46-427db209646d"
      },
      "source": [
        "b = np.logspace(0, 3, 12)\n",
        "print(b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[   1.            1.87381742    3.51119173    6.57933225   12.32846739\n",
            "   23.101297     43.28761281   81.11308308  151.9911083   284.80358684\n",
            "  533.66992312 1000.        ]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "6tzHNTTP_utP"
      },
      "source": [
        "# 2. Операции над одномерными массивами."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FCJIPaY7_utP"
      },
      "source": [
        "***Все арифметические операции производятся поэлементно.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "YPxEOhty_utP",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a945aace-fe42-445b-954a-38e0536affa7"
      },
      "source": [
        "print(a)\n",
        "print(b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ 3.  6.  9. 12. 15. 18. 21. 24. 27. 30. 33.]\n",
            "[ -2.  -4.  -6.  -8. -10. -12. -14. -16. -18. -20. -22.]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "GnjOwnni_utP",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "47f8aaf4-746f-44ee-a1ca-2d6fbf42b387"
      },
      "source": [
        "a = np.linspace(3, 33, 11)\n",
        "b = np.linspace(-2, -22, 11)\n",
        "print(a + b)\n",
        "print(a - b)\n",
        "print(a * b)\n",
        "print(a / b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11.]\n",
            "[ 5. 10. 15. 20. 25. 30. 35. 40. 45. 50. 55.]\n",
            "[  -6.  -24.  -54.  -96. -150. -216. -294. -384. -486. -600. -726.]\n",
            "[-1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5 -1.5]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "X4Dl5ZPq_utQ"
      },
      "source": [
        "***Один из операндов может быть скаляром, а не массивом.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "VOCLmN8I_utQ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a80e571a-e75d-4a6b-bae1-ac767adb8ea0"
      },
      "source": [
        "print(5*a)\n",
        "print(10 + b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ 15.  30.  45.  60.  75.  90. 105. 120. 135. 150. 165.]\n",
            "[  8.   6.   4.   2.   0.  -2.  -4.  -6.  -8. -10. -12.]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "iLPBYyBzEt0v",
        "outputId": "339caf9f-33a4-4c26-cb66-612a6bc9eb59"
      },
      "source": [
        "print((a + b) ** 2)\n",
        "print(2 ** (a + b))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[  1.   4.   9.  16.  25.  36.  49.  64.  81. 100. 121.]\n",
            "[2.000e+00 4.000e+00 8.000e+00 1.600e+01 3.200e+01 6.400e+01 1.280e+02\n",
            " 2.560e+02 5.120e+02 1.024e+03 2.048e+03]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lX1xixEw_utQ"
      },
      "source": [
        "***Если типы элементов разные, то идет каст к большему.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "eC__TA-u_utQ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "9206d942-a483-4d21-d6f9-8468172d1e0b"
      },
      "source": [
        "print(a + np.arange(11, dtype='int16'))\n",
        "print(type(a[0]))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ 3.  7. 11. 15. 19. 23. 27. 31. 35. 39. 43.]\n",
            "<class 'numpy.float64'>\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "QjnNr58x_utQ"
      },
      "source": [
        "***В ``Numpy`` есть элементарные функции, которые тоже применяются к массивам поэлементно. Они называются универсальными функциями (``ufunc``).***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vQDs6bTv_utR",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "352ac02e-0d3e-4894-8f24-2aa4098eac0c"
      },
      "source": [
        "type(np.cos)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "numpy.ufunc"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 35
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8J_xxASK_utR",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7f4a2856-4ac9-4989-a330-43eb950c07a9"
      },
      "source": [
        "np.cos(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([-0.9899925 ,  0.96017029, -0.91113026,  0.84385396, -0.75968791,\n",
              "        0.66031671, -0.54772926,  0.42417901, -0.29213881,  0.15425145,\n",
              "       -0.01327675])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 36
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DiAqTLSn_utR",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "43c21e86-7c6e-4bd6-d5a2-d1a79ca7f0f4"
      },
      "source": [
        "np.log(b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([nan, nan, nan, nan, nan, nan, nan, nan, nan, nan, nan])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 37
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "mA75T51o_utR"
      },
      "source": [
        "***Логические операции также производятся поэлементно.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "bxg7QoL1_utR",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "bc8e0a6f-0f8e-44cc-8e88-5b8bd820068c"
      },
      "source": [
        "print(a > b)\n",
        "print(a == b)\n",
        "print(a >= 10)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ True  True  True  True  True  True  True  True  True  True  True]\n",
            "[False False False False False False False False False False False]\n",
            "[False False False  True  True  True  True  True  True  True  True]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "9cA9X0SV_utR"
      },
      "source": [
        "***Кванторы ``всеобщности`` и ``существования``.***\n",
        "$$\\forall$$\n",
        "$$\\exists$$"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "v_AB-tbW_utS",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "cc0da6d0-1748-47c4-c4eb-fda6d6a89dcb"
      },
      "source": [
        "c = np.arange(0., 20)\n",
        "print(type(c[0]))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "<class 'numpy.float64'>\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "TTXpq1jn_utS",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "98a50efc-b5fe-4b68-9d54-8f846ea5a15a"
      },
      "source": [
        "np.any(c == 0.), np.all(c)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(True, False)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 41
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Y5TULOdL_utS"
      },
      "source": [
        "***Inplace операции.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "QDVEdz24_utS",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "371f7312-62b6-4787-8ac7-708e65f5e8e1"
      },
      "source": [
        "c += np.sin(4)\n",
        "print(c)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-0.7568025  0.2431975  1.2431975  2.2431975  3.2431975  4.2431975\n",
            "  5.2431975  6.2431975  7.2431975  8.2431975  9.2431975 10.2431975\n",
            " 11.2431975 12.2431975 13.2431975 14.2431975 15.2431975 16.2431975\n",
            " 17.2431975 18.2431975]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "blkndMit_utS"
      },
      "source": [
        "***Inplace операции возможны только для операндов одинакового типа.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "0a_JWFbm_utT",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "51ccd867-3599-421b-a5f4-55ff9051272b"
      },
      "source": [
        "c *= 2\n",
        "print(c)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-1.51360499  0.48639501  2.48639501  4.48639501  6.48639501  8.48639501\n",
            " 10.48639501 12.48639501 14.48639501 16.48639501 18.48639501 20.48639501\n",
            " 22.48639501 24.48639501 26.48639501 28.48639501 30.48639501 32.48639501\n",
            " 34.48639501 36.48639501]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "u2yCY0SZ_utT",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "2ac8590e-1f29-4d01-c4d9-4de0b1a249ee"
      },
      "source": [
        "b = np.arange(1., 21, 1)\n",
        "\n",
        "d = (b + c)\n",
        "d /= b\n",
        "print(d)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-0.51360499  1.2431975   1.82879834  2.12159875  2.297279    2.41439917\n",
            "  2.49805643  2.56079938  2.60959945  2.6486395   2.68058136  2.70719958\n",
            "  2.72972269  2.74902821  2.76575967  2.78039969  2.79331735  2.80479972\n",
            "  2.81507342  2.82431975]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "RGMwCAcI_utT"
      },
      "source": [
        "***При делении ``ndarray`` на нули, исключения не бросается.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "otVra42G_utT",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ea23d243-8faa-4658-b2db-2fe18a532445"
      },
      "source": [
        "print(np.array([0.0, 0.0, 1.0, -1.0]) / np.array([1.0, 0.0, 0.0, 0.0]))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[  0.  nan  inf -inf]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5ltLVqR6_utT"
      },
      "source": [
        "***Могут понадобится константы.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "DEFQmPV6_utU",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4fb93245-62f9-46d1-f505-a7aebd652aed"
      },
      "source": [
        "print(np.e, np.pi)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "2.718281828459045 3.141592653589793\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "_VMepMXJ_utU",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "43530600-ede3-464f-903b-c4963a6412bd"
      },
      "source": [
        "print(b)\n",
        "print(b.cumsum())"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ 1.  2.  3.  4.  5.  6.  7.  8.  9. 10. 11. 12. 13. 14. 15. 16. 17. 18.\n",
            " 19. 20.]\n",
            "[  1.   3.   6.  10.  15.  21.  28.  36.  45.  55.  66.  78.  91. 105.\n",
            " 120. 136. 153. 171. 190. 210.]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "2CfCkU_Q_utU"
      },
      "source": [
        "***Посмотрим на сортировку numpy-массивов.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "76_uCJUr_utU"
      },
      "source": [
        "a = np.array([1, 5, 6, 10, -2, 0, 18])"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "eTDAjZJu_utU",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "2ae77bf2-2bd7-430b-bf73-e7be1e4fe3f8"
      },
      "source": [
        "print(np.sort(a))\n",
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-2  0  1  5  6 10 18]\n",
            "[ 1  5  6 10 -2  0 18]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "95pzhn5c_utU"
      },
      "source": [
        "***Теперь попробуем как метод.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "SFm__ynY_utV",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "5a58701f-148f-4953-cb62-3401bf46d98e"
      },
      "source": [
        "a.sort()\n",
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-2  0  1  5  6 10 18]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qWer1GNA_utV",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "46e6e49c-bcce-4c97-dabb-c2accd211113"
      },
      "source": [
        "b = np.ones(5)\n",
        "b"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([1., 1., 1., 1., 1.])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 51
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "WVKJqS7v_utV"
      },
      "source": [
        "***Объединим массивы.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "wrspt4mM_utV",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "91233305-2b44-4366-9013-89c733aa3616"
      },
      "source": [
        "c = np.hstack((a, b, 5*b))\n",
        "c"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([-2.,  0.,  1.,  5.,  6., 10., 18.,  1.,  1.,  1.,  1.,  1.,  5.,\n",
              "        5.,  5.,  5.,  5.])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 52
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "jM8DmW5Q_utV"
      },
      "source": [
        "***Расщепление массива.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "mMvuAxlj_utW",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "26b85e1c-6048-45ae-96c4-4f47aee93562"
      },
      "source": [
        "x1, x2, x3, x4 = np.hsplit(a, [3, 5, 6])\n",
        "print(a)\n",
        "print(x1)\n",
        "print(x2)\n",
        "print(x3)\n",
        "print(x4)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-2  0  1  5  6 10 18]\n",
            "[-2  0  1]\n",
            "[5 6]\n",
            "[10]\n",
            "[18]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Imk9j8A7_utW"
      },
      "source": [
        "***Функции ``append`` ``delete`` ``insert`` не Inplace функции.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "0nOhUZkx_utW",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f0c46012-b005-43bd-ea21-1830eedb0a3a"
      },
      "source": [
        "print(np.delete(a, [2, 4, 1]))\n",
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-2  5 10 18]\n",
            "[-2  0  1  5  6 10 18]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8SUQlo2s_utW",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e9149b3a-70e5-4d88-bc5c-a20cea067ba9"
      },
      "source": [
        "np.insert(a, 2, [-1, -1])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([-2,  0, -1, -1,  1,  5,  6, 10, 18])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 55
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "qZeLBbQ4_utX",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e8c835e2-7e40-4451-e6df-de7397e2f9df"
      },
      "source": [
        "np.append(a, [2.2, 2.1])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([-2. ,  0. ,  1. ,  5. ,  6. , 10. , 18. ,  2.2,  2.1])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 56
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "EY8LCSPn_utX"
      },
      "source": [
        "## Индексирование массивов и срезы"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YrQOJXlT_utX"
      },
      "source": [
        "***Массив в обратном порядоке.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "w1EGOsVW_utX",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "dfedb93e-5ec9-4962-a0e0-1edd8ac41467"
      },
      "source": [
        "a[::-1]"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([18, 10,  6,  5,  1,  0, -2])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 57
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7LUt5Rtq_utY"
      },
      "source": [
        "***Диапазон индексов. Создаётся новый заголовок массива, указывающий на те же данные. Изменения, сделанные через такой массив, видны и в исходном массиве.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Qv-Ijg_k_utY",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "07383803-f0ec-4b24-a1c2-201d3221a499"
      },
      "source": [
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-2  0  1  5  6 10 18]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "h1taQuOu_utY",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "93c9891b-abcd-43c9-a213-03a6f535af18"
      },
      "source": [
        "a[2:5]"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "array([1, 5, 6])"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 59
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "OEzQjMOJ_utY",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "4f3ab682-d705-4f31-cf3e-d30bbbdd2c02"
      },
      "source": [
        "b = a[0:6] # копия не создается\n",
        "b[1] = -1000\n",
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[   -2 -1000     1     5     6    10    18]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FzN23mz7_utY"
      },
      "source": [
        "***Диапозоны с шагами.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "SZJMk-Yy_utZ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "44c0cbba-a6a9-4724-9d2e-bb50c3833de2"
      },
      "source": [
        "b = a[0:4:2]\n",
        "print(b)\n",
        "\n",
        "# подмассиву можно присваивать скаляр\n",
        "a[1:6:3] = 0\n",
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-2  1]\n",
            "[-2  0  1  5  0 10 18]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7uzmZNXf_utZ"
      },
      "source": [
        "***Чтобы скопировать и данные массива, нужно использовать метод ``copy``.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "W-KuaU4W_utZ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "71be91a2-7f50-44ee-ce13-57b9329f42a2"
      },
      "source": [
        "b = a.copy()\n",
        "b[2] = -4\n",
        "print(b)\n",
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[-2  0 -4  5  0 10 18]\n",
            "[-2  0  1  5  0 10 18]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "BbQnlrci_utZ",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "982b61de-ee09-4137-d2a1-dadf32f212aa"
      },
      "source": [
        "print(a[[5,3,1]]) # массив индексов"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[10  5  0]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "juHM0Uww_utZ"
      },
      "source": [
        "**Задание 3:**  \n",
        "- Создать массив чисел от $-4\\pi$  до $4\\pi $, количество точек 100\n",
        "- Посчитать сумму поэлементных квадратов синуса и косинуса для данного массива  \n",
        "- С помощью ``np.all`` проверить, что все элементы равны единице."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "b0RGOEuk_uta",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "030dca66-a18a-4629-e5d4-c99057de41bd"
      },
      "source": [
        "# решение\n",
        "\n",
        "x = np.linspace(-4*np.pi, 4*np.pi, 100)\n",
        "\n",
        "np.all((np.sin(x)**2 + np.cos(x)**2).round() == 1)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "True"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 64
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "lkvf6MZ0_uta"
      },
      "source": [
        "# 3. Двумерные массивы"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "YQuMJe26_utb",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "734d0f3b-de02-4c3a-ccff-ae15e9d2f0ba"
      },
      "source": [
        "a = np.array([[1, 2], [3, 4]])\n",
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[1 2]\n",
            " [3 4]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "AKY6TxVM_utb",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "fb077b79-e488-4f54-eb4b-b5926cf267dc"
      },
      "source": [
        "a.ndim, a.shape, len(a), a.size"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(2, (2, 2), 2, 4)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 66
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "iqD53O2Q_utb"
      },
      "source": [
        "***Обращение по индексу.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "4JPJofyc_utb",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b07fcacd-9b87-439f-a134-24116ba98aed"
      },
      "source": [
        "a[1][1], a[1,1]"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "(4, 4)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 67
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "FaKeSQN1_utc"
      },
      "source": [
        "***Атрибуту ``shape`` можно присвоить новое значение -- кортеж размеров по всем координатам. Получится новый заголовок массива; его данные не изменятся.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "8htEwSLX_utc",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "2930e007-0f31-45ea-e5da-055c5d9d375b"
      },
      "source": [
        "b = np.arange(0, 20)\n",
        "b.shape = (2, 10)\n",
        "print(b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[ 0  1  2  3  4  5  6  7  8  9]\n",
            " [10 11 12 13 14 15 16 17 18 19]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Ez423-By_utc",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ce16f86a-bb14-4063-96f0-7c3219ba586f"
      },
      "source": [
        "print(b.ravel()) # стягивание в одномерный массив"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "-4vrqJGY_utc",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "6924a437-da70-40bb-a691-02ae8bbeee74"
      },
      "source": [
        "a = np.ones((3, 3)) # подать tuple\n",
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[1. 1. 1.]\n",
            " [1. 1. 1.]\n",
            " [1. 1. 1.]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "jxVHN_Qf_utc",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "c02dd521-6210-477d-95e2-babc07372933"
      },
      "source": [
        "b = np.zeros((3, 4))\n",
        "print(b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[0. 0. 0. 0.]\n",
            " [0. 0. 0. 0.]\n",
            " [0. 0. 0. 0.]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "pqYaQeGE_utd",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "90704f11-dfb3-4e48-deab-888bb34f7931"
      },
      "source": [
        "c = np.eye(3)\n",
        "print(c)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[1. 0. 0.]\n",
            " [0. 1. 0.]\n",
            " [0. 0. 1.]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "V_FgSMPx_utd",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "60ad2e1c-2fd9-49c6-f0f9-52ee6e5cb456"
      },
      "source": [
        "d = np.diag(np.array([1, 2, 3, 4]))\n",
        "print(d)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[1 0 0 0]\n",
            " [0 2 0 0]\n",
            " [0 0 3 0]\n",
            " [0 0 0 4]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "3Z3_1h8d_utd"
      },
      "source": [
        "***Задание 4:***\n",
        "Создать квадратную матрицу размера 8, на главной диаг. арифметическая прогрессия с шагом 3 (начиная с 3), а на побочной -1, остальные элементы 0."
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "vufyLtGG_utd",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "46351253-ae09-49e5-d4ab-61f36d200c48"
      },
      "source": [
        "# решение\n",
        "\n",
        "a = -1*np.eye(8)[::-1] + np.diag(np.arange(3, 27, 3))\n",
        "print(a)\n"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[ 3.  0.  0.  0.  0.  0.  0. -1.]\n",
            " [ 0.  6.  0.  0.  0.  0. -1.  0.]\n",
            " [ 0.  0.  9.  0.  0. -1.  0.  0.]\n",
            " [ 0.  0.  0. 12. -1.  0.  0.  0.]\n",
            " [ 0.  0.  0. -1. 15.  0.  0.  0.]\n",
            " [ 0.  0. -1.  0.  0. 18.  0.  0.]\n",
            " [ 0. -1.  0.  0.  0.  0. 21.  0.]\n",
            " [-1.  0.  0.  0.  0.  0.  0. 24.]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Dzkh3dPi_utd"
      },
      "source": [
        "***Умножение матриц.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nXuMZb_g_ute",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "7d1f0518-ffcd-4f04-abde-b942c56b1ac8"
      },
      "source": [
        "a = 5*np.ones((5, 5))\n",
        "b = np.eye(5) + 1\n",
        "print(a, '\\n')\n",
        "print(b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[5. 5. 5. 5. 5.]\n",
            " [5. 5. 5. 5. 5.]\n",
            " [5. 5. 5. 5. 5.]\n",
            " [5. 5. 5. 5. 5.]\n",
            " [5. 5. 5. 5. 5.]] \n",
            "\n",
            "[[2. 1. 1. 1. 1.]\n",
            " [1. 2. 1. 1. 1.]\n",
            " [1. 1. 2. 1. 1.]\n",
            " [1. 1. 1. 2. 1.]\n",
            " [1. 1. 1. 1. 2.]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "t5cZ2JrD_ute",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "5e99bfbe-62b3-4044-b267-005eb261cf02"
      },
      "source": [
        "print(a*b, '\\n') # поэлементное умножение\n",
        "print(a @ b, '\\n') # матричное умножение\n",
        "print(a.dot(b)) "
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[10.  5.  5.  5.  5.]\n",
            " [ 5. 10.  5.  5.  5.]\n",
            " [ 5.  5. 10.  5.  5.]\n",
            " [ 5.  5.  5. 10.  5.]\n",
            " [ 5.  5.  5.  5. 10.]] \n",
            "\n",
            "[[30. 30. 30. 30. 30.]\n",
            " [30. 30. 30. 30. 30.]\n",
            " [30. 30. 30. 30. 30.]\n",
            " [30. 30. 30. 30. 30.]\n",
            " [30. 30. 30. 30. 30.]] \n",
            "\n",
            "[[30. 30. 30. 30. 30.]\n",
            " [30. 30. 30. 30. 30.]\n",
            " [30. 30. 30. 30. 30.]\n",
            " [30. 30. 30. 30. 30.]\n",
            " [30. 30. 30. 30. 30.]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "IUOuqGs9_ute"
      },
      "source": [
        "***Двумерные массивы, зависящие только от одного индекса: $x_{ij}=u_j$, $y_{ij}=v_i$***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "JnSaSi4l_ute",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "dcb6d68e-bbb0-40be-ac2e-5b16afe3f230"
      },
      "source": [
        "u = np.linspace(1, 2, 2)\n",
        "v = np.linspace(4, 8, 3)\n",
        "print(u)\n",
        "print(v)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[1. 2.]\n",
            "[4. 6. 8.]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Y4bCapBi_ute",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ce8bec09-d962-4e22-992e-07c738902454"
      },
      "source": [
        "x, y = np.meshgrid(u, v)\n",
        "print(x, '\\n')\n",
        "print(y)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[1. 2.]\n",
            " [1. 2.]\n",
            " [1. 2.]] \n",
            "\n",
            "[[4. 4.]\n",
            " [6. 6.]\n",
            " [8. 8.]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "26usJHTD_utf",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "94e65f5a-533f-4bc5-a2c5-0d277caf87f1"
      },
      "source": [
        "print(x.reshape(6)) # то же самое, что и shape"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[1. 2. 1. 2. 1. 2.]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "32M0HsA7_utg"
      },
      "source": [
        "***Задание 5:***\n",
        "- Отобразить вектор размера 100, в котором вычеркивается **x**, если **x** --- составное (т. е. не является простым)"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Gty7eFic_utg"
      },
      "source": [
        "is_prime = np.ones(100, dtype=bool)"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "18EkFa_T_utg"
      },
      "source": [
        "is_prime[:2] = False"
      ],
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nffcK9Bz_utg",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "0a4cd2b9-325c-492c-b571-a4d9f7940a98"
      },
      "source": [
        "N_max = int(np.sqrt(len(is_prime)))\n",
        "for i in range(2, N_max):\n",
        "    is_prime[2*i::i] = False # начинаем с 2i с шагом i\n",
        "    \n",
        "print(is_prime)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[False False  True  True False  True False  True False False False  True\n",
            " False  True False False False  True False  True False False False  True\n",
            " False False False False False  True False  True False False False False\n",
            " False  True False False False  True False  True False False False  True\n",
            " False False False False False  True False False False False False  True\n",
            " False  True False False False False False  True False False False  True\n",
            " False  True False False False False False  True False False False  True\n",
            " False False False False False  True False False False False False False\n",
            " False  True False False]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "BP_bXlNdnZM9",
        "outputId": "1ffa22c2-f863-401c-f39d-98a16fbd1a42"
      },
      "source": [
        "print(is_prime[17])\n",
        "print(is_prime[25])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "True\n",
            "False\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "YSBsopHn_uth"
      },
      "source": [
        "***Маски.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "r4OSDlK3_uth",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "685adb4a-d0b0-4d09-d814-e41da732c497"
      },
      "source": [
        "a = np.arange(20)\n",
        "print(a % 3 == 0)\n",
        "print(a[a % 3 == 0])"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ True False False  True False False  True False False  True False False\n",
            "  True False False  True False False  True False]\n",
            "[ 0  3  6  9 12 15 18]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "7YKwXJIw_uth"
      },
      "source": [
        "***След (trace) - сумма диагональных элементов.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "H5gVZbGH_uth",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "af712b03-64d4-4211-e7f7-acbed0d28b7b"
      },
      "source": [
        "b = np.diag(a[a >= 10])\n",
        "print(b)\n",
        "print(np.trace(b))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[10  0  0  0  0  0  0  0  0  0]\n",
            " [ 0 11  0  0  0  0  0  0  0  0]\n",
            " [ 0  0 12  0  0  0  0  0  0  0]\n",
            " [ 0  0  0 13  0  0  0  0  0  0]\n",
            " [ 0  0  0  0 14  0  0  0  0  0]\n",
            " [ 0  0  0  0  0 15  0  0  0  0]\n",
            " [ 0  0  0  0  0  0 16  0  0  0]\n",
            " [ 0  0  0  0  0  0  0 17  0  0]\n",
            " [ 0  0  0  0  0  0  0  0 18  0]\n",
            " [ 0  0  0  0  0  0  0  0  0 19]]\n",
            "145\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "isiWgLWK_uti"
      },
      "source": [
        "# 4. Тензоры (многомерные массивы)"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "AUyIWgP2_uti",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "406af1ac-3935-4d4d-d1f7-38399fc7d90f"
      },
      "source": [
        "X = np.arange(64).reshape(8, 2, 4)\n",
        "print(X)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[[ 0  1  2  3]\n",
            "  [ 4  5  6  7]]\n",
            "\n",
            " [[ 8  9 10 11]\n",
            "  [12 13 14 15]]\n",
            "\n",
            " [[16 17 18 19]\n",
            "  [20 21 22 23]]\n",
            "\n",
            " [[24 25 26 27]\n",
            "  [28 29 30 31]]\n",
            "\n",
            " [[32 33 34 35]\n",
            "  [36 37 38 39]]\n",
            "\n",
            " [[40 41 42 43]\n",
            "  [44 45 46 47]]\n",
            "\n",
            " [[48 49 50 51]\n",
            "  [52 53 54 55]]\n",
            "\n",
            " [[56 57 58 59]\n",
            "  [60 61 62 63]]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "5rOaCZPA_uti",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a686ac1c-817d-4e8d-a743-a2fa33e77d18"
      },
      "source": [
        "X.shape, len(X), X.size, X.ndim"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "((8, 2, 4), 8, 64, 3)"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 90
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "5CAEcdZD_uti"
      },
      "source": [
        "***Посмотрим на суммы по разным осям.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "C5GLpba__uti",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "f37d2076-270a-4943-b8d6-c6dc1eeefe2b"
      },
      "source": [
        "print(np.sum(X, axis=0), '\\n')\n",
        "print(np.sum(X, axis=1), '\\n')\n",
        "print(np.sum(X, axis=2), '\\n')\n",
        "\n",
        "# суммируем сразу по двум осям, то есть для фиксированной i \n",
        "# суммируем только элементы с индексами (i, *, *)\n",
        "print(np.sum(X, axis=(1, 2)))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[224 232 240 248]\n",
            " [256 264 272 280]] \n",
            "\n",
            "[[  4   6   8  10]\n",
            " [ 20  22  24  26]\n",
            " [ 36  38  40  42]\n",
            " [ 52  54  56  58]\n",
            " [ 68  70  72  74]\n",
            " [ 84  86  88  90]\n",
            " [100 102 104 106]\n",
            " [116 118 120 122]] \n",
            "\n",
            "[[  6  22]\n",
            " [ 38  54]\n",
            " [ 70  86]\n",
            " [102 118]\n",
            " [134 150]\n",
            " [166 182]\n",
            " [198 214]\n",
            " [230 246]] \n",
            "\n",
            "[ 28  92 156 220 284 348 412 476]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "A30UqUOO_utj"
      },
      "source": [
        "# 5. Линейная алгебра"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "L9yyZxD1_utj",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "9f923450-d516-4e29-fa03-fe93ba618af8"
      },
      "source": [
        "a = np.array([[2, 1], [2, 3]])\n",
        "print(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[2 1]\n",
            " [2 3]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "vPaPbS4i_utj"
      },
      "source": [
        "***Определитель.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "iAEMomd4_utj",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "02f2781f-7b7a-4987-cada-ea60c0fe44e2"
      },
      "source": [
        "np.linalg.det(a)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "execute_result",
          "data": {
            "text/plain": [
              "4.0"
            ]
          },
          "metadata": {
            "tags": []
          },
          "execution_count": 93
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "NyXE5jgh_utj"
      },
      "source": [
        "***Нахождениия обратной.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "Arj57Cqz_utj",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "3e08097e-89fd-4fc6-da84-748b168f91e9"
      },
      "source": [
        "b = np.linalg.inv(a)\n",
        "print(b)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[ 0.75 -0.25]\n",
            " [-0.5   0.5 ]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "yWNVSSJv_utk",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "1c46ed14-7079-4d44-fe13-fe9be147fd85"
      },
      "source": [
        "print(a.dot(b))\n",
        "print(b.dot(a))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[1. 0.]\n",
            " [0. 1.]]\n",
            "[[1. 0.]\n",
            " [0. 1.]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "id": "mgIdQiNDFY5L",
        "outputId": "d685469d-ef49-47d6-8666-c46e17e9dfc5"
      },
      "source": [
        "c = np.array([[2, 1], [6, 3]])\n",
        "print(c)\n",
        "print(np.linalg.det(c))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[[2 1]\n",
            " [6 3]]\n",
            "0.0\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "colab": {
          "base_uri": "https://localhost:8080/",
          "height": 341
        },
        "id": "hFFsQKv4FgYV",
        "outputId": "3fa3a00d-df53-4cbb-dc9b-bf2888c7e5ef"
      },
      "source": [
        "np.linalg.inv(c)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "error",
          "ename": "LinAlgError",
          "evalue": "ignored",
          "traceback": [
            "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
            "\u001b[0;31mLinAlgError\u001b[0m                               Traceback (most recent call last)",
            "\u001b[0;32m<ipython-input-97-5ed58b2836e1>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m()\u001b[0m\n\u001b[0;32m----> 1\u001b[0;31m \u001b[0mnp\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mlinalg\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0minv\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mc\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
            "\u001b[0;32m<__array_function__ internals>\u001b[0m in \u001b[0;36minv\u001b[0;34m(*args, **kwargs)\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py\u001b[0m in \u001b[0;36minv\u001b[0;34m(a)\u001b[0m\n\u001b[1;32m    544\u001b[0m     \u001b[0msignature\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0;34m'D->D'\u001b[0m \u001b[0;32mif\u001b[0m \u001b[0misComplexType\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mt\u001b[0m\u001b[0;34m)\u001b[0m \u001b[0;32melse\u001b[0m \u001b[0;34m'd->d'\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    545\u001b[0m     \u001b[0mextobj\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0mget_linalg_error_extobj\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0m_raise_linalgerror_singular\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m--> 546\u001b[0;31m     \u001b[0mainv\u001b[0m \u001b[0;34m=\u001b[0m \u001b[0m_umath_linalg\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0minv\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0ma\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0msignature\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0msignature\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mextobj\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0mextobj\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m    547\u001b[0m     \u001b[0;32mreturn\u001b[0m \u001b[0mwrap\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mainv\u001b[0m\u001b[0;34m.\u001b[0m\u001b[0mastype\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mresult_t\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mcopy\u001b[0m\u001b[0;34m=\u001b[0m\u001b[0;32mFalse\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m    548\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;32m/usr/local/lib/python3.6/dist-packages/numpy/linalg/linalg.py\u001b[0m in \u001b[0;36m_raise_linalgerror_singular\u001b[0;34m(err, flag)\u001b[0m\n\u001b[1;32m     86\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     87\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_raise_linalgerror_singular\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0merr\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mflag\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m---> 88\u001b[0;31m     \u001b[0;32mraise\u001b[0m \u001b[0mLinAlgError\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0;34m\"Singular matrix\"\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m\u001b[1;32m     89\u001b[0m \u001b[0;34m\u001b[0m\u001b[0m\n\u001b[1;32m     90\u001b[0m \u001b[0;32mdef\u001b[0m \u001b[0m_raise_linalgerror_nonposdef\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0merr\u001b[0m\u001b[0;34m,\u001b[0m \u001b[0mflag\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m:\u001b[0m\u001b[0;34m\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n",
            "\u001b[0;31mLinAlgError\u001b[0m: Singular matrix"
          ]
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "24c7Zzvz_utk"
      },
      "source": [
        "***Решение НЛУ.***\n",
        "$$ A \\cdot x = v $$"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "l0aHvZ_y_utk",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "b717007c-14d9-410b-953b-2c59e1e7b4e6"
      },
      "source": [
        "v = np.array([5, -10])\n",
        "print(np.linalg.solve(a, v))\n",
        "print(b.dot(v))"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[ 6.25 -7.5 ]\n",
            "[ 6.25 -7.5 ]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "f-NrxHvy_utk"
      },
      "source": [
        "***Найдем собственные вектора матрицы A.***\n",
        "$$ A \\cdot x = \\lambda \\cdot x $$"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "whDG4FcZ_utk",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "a3f69768-43d2-4abb-87b2-e983c78acb78"
      },
      "source": [
        "l, u = np.linalg.eig(a)\n",
        "print(l)\n",
        "print(u)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[1. 4.]\n",
            "[[-0.70710678 -0.4472136 ]\n",
            " [ 0.70710678 -0.89442719]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "czfrs56I_utk"
      },
      "source": [
        "***Собственные значения матриц A и A.T совпадают.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "9ke3c0MH_utl",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "ff857e21-eb35-43d3-c01d-3b31d29ad302"
      },
      "source": [
        "l, u = np.linalg.eig(a.T)\n",
        "print(l)\n",
        "print(u)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[1. 4.]\n",
            "[[-0.89442719 -0.70710678]\n",
            " [ 0.4472136  -0.70710678]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "sHqgbKG1_utl",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "8551ea20-4f61-431f-e129-f0fcb5670384"
      },
      "source": [
        "l, u = np.linalg.eig(np.eye(3))\n",
        "print(l)\n",
        "print(u)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "[1. 1. 1.]\n",
            "[[1. 0. 0.]\n",
            " [0. 1. 0.]\n",
            " [0. 0. 1.]]\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "x6DE6oKj_utl"
      },
      "source": [
        "***Производительность.***"
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "eG_43zlf_utl",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "43831b81-e04f-4686-c39b-d7335aa17965"
      },
      "source": [
        "%%time\n",
        "\n",
        "sum_value = np.sum(np.arange(10**7))\n",
        "print(sum_value)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "49999995000000\n",
            "CPU times: user 85 ms, sys: 17 ms, total: 102 ms\n",
            "Wall time: 105 ms\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "code",
      "metadata": {
        "id": "nJMt7YsM_uto",
        "colab": {
          "base_uri": "https://localhost:8080/"
        },
        "outputId": "e423f1bd-7dca-42f5-ea43-08c87457939e"
      },
      "source": [
        "%%time\n",
        "arr = 5*np.arange(10**7)"
      ],
      "execution_count": null,
      "outputs": [
        {
          "output_type": "stream",
          "text": [
            "CPU times: user 27.2 ms, sys: 0 ns, total: 27.2 ms\n",
            "Wall time: 28.3 ms\n"
          ],
          "name": "stdout"
        }
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "VAnhPlAL_utp"
      },
      "source": [
        "# Полезные ссылки"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rpukgcep_utp"
      },
      "source": [
        "[Введение в Анализ Данных](https://mipt-stats.gitlab.io/jekyll/update/2020/02/01/ad.html)\n",
        "\n",
        "[GitHub NumPy](https://github.com/numpy/numpy)\n",
        "\n",
        "[Документация по NumPy](https://numpy.org/doc/stable/)\n",
        "\n",
        "[mlcource.ai](https://mlcourse.ai)"
      ]
    }
  ]
}